class Stage < ActiveRecord::Base
  belongs_to :project
  has_and_belongs_to_many :work_item_types
  has_many :designer_work_items, :dependent => :destroy
  has_many :work_items, :dependent => :destroy

  validates_presence_of :project_id,
    :name,
    :started_on,
    :ended_on
  validates_presence_of :payed_on,
    :if => Proc.new { |stage| stage.payed? }
  validates_uniqueness_of :name,
    :scope => :project_id

  default_scope :order => 'updated_at desc'

  def reset_should_be_payed!
    self.should_be_payed = DesignerWorkItem.sum(:should_be_payed,
      :conditions => {
        :stage_id => id
      }
    )
  end

  def designers
     Designer.all :conditions => [
      'designer_work_items.stage_id = ? ',
      id
    ],
    :include => :designer_work_items
  end

  def designers_by_work_item_type_id(work_item_type_id)
     Designer.all :conditions => [
      'designer_work_items.work_item_type_id = ? and designer_work_items.stage_id = ? ',
      work_item_type_id,
      id
    ],
    :include => :designer_work_items
  end

  def designer_work_items_by_work_item_type_id(work_item_type_id)
     DesignerWorkItem.all :conditions => [
        'work_item_type_id = ? and stage_id = ?',
        work_item_type_id,
        id
      ],
        :order => 'created_at asc'
  end
  
  def work_items_by_work_item_type_id(work_item_type_id)
    WorkItem.find_all_by_stage_id_and_work_item_type_id(id,work_item_type_id)
  end

  def payed?
    pay_status == 'payed'
  end

  def paying?
    pay_status == 'paying'
  end

  def paused?
    pay_status == 'paused'
  end

  def after_save
    project.reset_stat!
    project.save!
  end

  def after_destroy
    project.reset_stat!
    project.save!
  end
  
  def clone!
    clone = Stage.create!(
      attributes.merge( 
        :name => "#{name}-克隆-#{count_by_name("%#{name}%克隆%") + 1}",
        :created_at => nil,
        :updated_at => nil
     )
    )
    work_item_types.each do |work_item_type|
      clone.work_item_types << work_item_type
    end
    work_items.each do |work_item|
      clone_work_item = WorkItem.create!(
        work_item.attributes.merge(
          :stage_id => clone.id,
          :created_at => nil,
          :updated_at => nil
        )        
      )
      work_item.designer_work_items.each do | designer_work_item |
        DesignerWorkItem.create!(
          designer_work_item.attributes.merge(
            :stage_id => clone.id,
            :work_item_id => clone_work_item.id,
            :created_at => nil,
            :updated_at => nil
          )
        )
      end
    end
    clone.save! and clone
  end
  
  def count_by_name(stage_name)
    Stage.count( 
      :conditions => [
        'name like ? and project_id = ? ',
        stage_name,
        project.id
      ]
    )
  end
  
end
